<template>
  <!-- 筛选区 -->
  <div class="sub-filter">
    <!-- 1.品牌（固定的） -->
    <div class="item">
      <div class="head">品牌：</div>
      <div class="body">
        <!-- <a href="javascript:;">全部</a> -->
        <a :class="{ active:brand.selected  }" @click="setBrand(brand)" href="javascript:;"  v-for="brand in subCategoryData.brands" :key="brand.id">{{ brand.name }}</a>
      </div>
    </div>

    <!-- 2.分类商品规格属性（不固定的，根据商品自身） -->
    <div class="item"  v-for="prd in subCategoryData.saleProperties" :key="prd.id">
      <div class="head">{{ prd.name }}：</div>
      <div class="body">
        <!-- <a href="javascript:;">全部</a> -->
        <a  @click="setPrd(per,prd)" :class="{ active: per.selected  }" href="javascript:;" v-for="per in prd.properties" :key="per.id">{{per.name}}</a>
      </div>
    </div>
  </div>
</template>
<script>
import { inject } from 'vue'
export default {
  name: 'SubFilter',
  setup () {
    // 接收父组件provide数据
    const subCategoryData = inject('subCateData')
    // 接收过滤条件数据
    const filterParams = inject('filterParams')

    // 处理品牌点击选中
    const setBrand = (currBrand) => {
      /**
       * 1.把之前的数据都改成未选中
       * 2.把当前点击的改成选中
       */
      // 如果已经选中了，就return
      if (currBrand.selected) return
      // console.log(subCategoryData.value)
      subCategoryData.value.brands.forEach(item => {
        item.selected = false
      })

      // 存储当前点击的品牌
      filterParams.value.brands = currBrand.id

      currBrand.selected = true
    }

    /**
     * 处理属性点击选中
     * currPer 当前点击的属性
     * currPers 当前点击所有属性的集合
     */
    const setPrd = (currPer, currPers) => {
      if (currPer.selected) return
      // console.log(currPer, currPers)
      currPers.properties.forEach(item => {
        item.selected = false
      })
      currPer.selected = true
      // 存储当前点击的商品属性(单选)
      /**
       * 1.不是全部的时候，新增条件
       * 2.每个属性groupName下，只能选择一个条件(单选)
       */
      // 排重 findIndex方法可以去重
      const index = filterParams.value.attrs.findIndex(item => currPers.name === item.groupName)
      if (index > -1) {
        filterParams.value.attrs.splice(index, 1)
      }
      // 新增
      if (currPer.id !== null) {
        filterParams.value.attrs.push({
          groupName: currPers.name, // 属性名
          propertyName: currPer.name // 属性名具体的值
        })
      }
    }

    return { subCategoryData, setBrand, setPrd }
  }

}
</script>
<style scoped lang='less'>
// 筛选区
.sub-filter {
  background: #fff;
  padding: 25px;
  .item {
    display: flex;
    padding: 10px 0;
    .head {
      width: 80px;
      color: #999;
    }
    .body {
      flex: 1;
      a {
        display: inline-block;
        margin-right: 36px;
        margin-bottom: 20px;
        transition: all 0.3s;
        border: 1px solid #eee;
        padding: 6px;
        // 高亮效果
        &.active,
        &:hover {
          color: @xtxColor;
          border-color: @xtxColor;
        }
      }
    }
  }
}
</style>
